var express = require('express')
var router = express.Router()

// 引入连接池对象
const sql = require('../db/index')
const Response = require('../utils/response')
// 引入token鉴权
const verifyToken = require('../utils/auth')
/**
 * @swagger
 * /product/findAll:
 *   get:
 *     summary: 获取所有订单产品
 *     tags: [产品]
 *     description: 查询数据库中的所有订单产品信息。
 *     responses:
 *       200:
 *         description: 查询成功，返回订单产品列表
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: '查询成功'
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       id:
 *                         type: integer
 *                         example: 1
 *                       product_name:
 *                         type: string
 *                         example: '产品A'
 *                       price:
 *                         type: number
 *                         format: float
 *                         example: 99.99
 *                       quantity:
 *                         type: integer
 *                         example: 10
 *       500:
 *         description: 服务器内部错误
 */
// 查询所有产品
router.get('/findAll', verifyToken, async (req, res) => {
  const [response] = await sql.query('select * from order_product')
  res.send(new Response(200, '查询成功', response))
})

/**
 * @swagger
 * /product/pageQuery:
 *   get:
 *     summary: 分页查询订单产品
 *     tags: [产品]
 *     description: 根据页面和页面大小参数分页查询订单产品信息。
 *     parameters:
 *       - name: page
 *         in: query
 *         required: true
 *         description: 当前页码
 *         schema:
 *           type: integer
 *           example: 1
 *       - name: pageSize
 *         in: query
 *         required: true
 *         description: 每页条数
 *         schema:
 *           type: integer
 *           example: 10
 *     responses:
 *       200:
 *         description: 查询成功，返回订单产品分页列表
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: '查询成功'
 *                 data:
 *                   type: object
 *                   properties:
 *                     total:
 *                       type: integer
 *                       example: 6
 *                     page:
 *                       type: integer
 *                       example: 1
 *                     pageSize:
 *                       type: integer
 *                       example: 10
 *                     list:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           id:
 *                             type: integer
 *                             example: 1
 *                           product_name:
 *                             type: string
 *                             example: '产品A'
 *                           price:
 *                             type: number
 *                             format: float
 *                             example: 99.99
 *                           quantity:
 *                             type: integer
 *                             example: 10
 *       500:
 *         description: 服务器内部错误
 */
// 分页查询产品数据
router.get('/pageQuery', async (req, res) => {
  // 获取地址栏参数
  const { page, pageSize } = req.query
  // console.log(page,pageSize);

  // 偏移量 从几条开始查询
  const offset = (page - 1) * pageSize
  const [totalCount] = await sql.query('select count(*) as count from order_product')
  const total = totalCount[0]
  // console.log(total);//{count:6}
  const [response] = await sql.query('select * from order_product limit ? offset ?', [parseInt(pageSize), offset])
  console.log(response);
  res.send(new Response(200, '查询成功', {
    total,
    page,
    pageSize,
    list: response,
  }))
})

/**
 * @swagger
 * /product/deleteById:
 *   delete:
 *     tags: [产品]
 *     summary: 根据ID删除订单产品
 *     description: 根据提供的ID删除对应的订单产品。
 *     parameters:
 *       - name: id
 *         in: query
 *         required: true
 *         description: 要删除的订单产品ID
 *         schema:
 *           type: integer
 *           example: 1
 *     responses:
 *       200:
 *         description: 删除成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: '删除成功'
 *                 data:
 *                   type: null
 *       500:
 *         description: 删除失败，ID未提供
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 500
 *                 message:
 *                   type: string
 *                   example: 'ID is required'
 *                 data:
 *                   type: null
 */
// 删除产品
router.delete('/deleteById', async (req, res) => {
  const { id } = req.query
  if (!id) {
    res.send(new Response(500, 'ID is required', null))
  } else {
    await sql.query('delete from order_product where id=?', [id])
    res.send(new Response(200, '删除成功', null))
  }
})

/**
 * @swagger
 * /product/saveOrUpdate:
 *   post:
 *     summary: 新增或修改产品
 *     tags: [产品]
 *     description: 该接口用于新增或修改产品信息。根据提供的 ID 判断是新增还是修改。
 *     requestBody:
 *       required: true
 *       content:
 *         application/x-www-form-urlencoded:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: integer
 *                 example: 1
 *                 description: 产品的唯一标识，存在则为修改，不存在则为新增。
 *               name:
 *                 type: string
 *                 example: "测试"
 *                 description: 产品名称。
 *               description:
 *                 type: string
 *                 example: "产品描述"
 *                 description: 产品详细描述。
 *               price:
 *                 type: double
 *                 example: 99
 *                 description: 产品价格。
 *               photo:
 *                 type: string
 *                 example: "NULL"
 *                 description: 产品照片的链接或路径，默认为 'NULL'。
 *               status:
 *                 type: string
 *                 example: "正常"
 *                 description: 产品状态，默认为 '正常'。
 *     responses:
 *       200:
 *         description: 操作成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "修改成功"  # 或 "新增成功"
 *                 data:
 *                   type: object
 *                   nullable: true
 */
// 新增或者修改
router.post('/saveOrUpdate', async (req, res) => {
  const { id, name, description, price, photo = 'null ', status = '正常' } = req.body
  // id是否存在
  if (id) {
    await sql.query('update order_product set name=?,description=?,price=?,photo=?,status=? where id=?', [name, description, price, photo, status, id])
    res.send(new Response(200, '修改成功', null))
  } else {
    sql.query('insert into order_product (name, description, price, photo,status) values (?,?,?,?,?)', [name, description, price, photo, status])
    res.send(new Response(200, '新增成功', null))

  }
})


/**
 * @swagger
 * /product/changeStatus:
 *   post:
 *     summary: 修改产品状态
 *     tags: [产品]
 *     description: 该接口用于修改产品的状态为“正常”或“下架”。
 *     requestBody:
 *       required: true
 *       content:
 *         application/x-www-form-urlencoded:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: integer
 *                 example: 1
 *                 description: 产品的唯一标识。
 *               status:
 *                 type: string
 *                 example: "下架"
 *                 description: 要修改的状态，可以是“下架”或“上架”。
 *     responses:
 *       200:
 *         description: 操作成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "下架成功"  # 或 "上架成功"
 *                 data:
 *                   type: object
 *                   nullable: true
 */
router.post('/changeStatus', async (req, res) => {
  let { id, status } = req.body
  status === '下架' ? status = '下架' : status = '正常'
  await sql.query('update order_product set status=? where id =?', [status, id])
  res.send(new Response(200, `${status} === '下架'` ? status = '下架' : status = '上架'))
}
)

/**
 * @swagger
 * /product/pageQueryFind:
 *   get:
 *     summary: 分页多条件查询产品
 *     tags: [产品]
 *     description: 根据可选的名称和状态过滤条件检索产品的分页列表。
 *     parameters:
 *       - name: page
 *         in: query
 *         required: true
 *         type: integer
 *         description: 要检索的页码（1-based）。
 *       - name: pageSize
 *         in: query
 *         required: true
 *         type: integer
 *         description: 每页产品的数量。
 *       - name: name
 *         in: query
 *         required: false
 *         type: string
 *         description: 产品名称的模糊匹配。
 *       - name: status
 *         in: query
 *         required: false
 *         type: string
 *         description: 产品状态的精确匹配。
 *     responses:
 *       200:
 *         description: 成功检索到产品列表。
 *         schema:
 *           type: object
 *           properties:
 *             code:
 *               type: integer
 *               example: 200
 *             message:
 *               type: string
 *               example: "查询成功"
 *             data:
 *               type: object
 *               properties:
 *                 list:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       id:
 *                         type: integer
 *                       name:
 *                         type: string
 *                       description:
 *                         type: string
 *                       price:
 *                         type: number
 *                         format: float
 *                       status:
 *                         type: string
 *                 total:
 *                   type: integer
 *                   description: 匹配查询的产品总数。
 *                 page:
 *                   type: integer
 *                   description: 当前页码。
 *                 pageSize:
 *                   type: integer
 *                   description: 每页产品的数量。
 *       400:
 *         description: 由于参数无效而导致的错误请求。
 *       500:
 *         description: 服务器内部错误。
 */
// 分页按条件进行模糊查询
router.get('/pageQueryFind', async (req, res) => {
  const { page, pageSize, name, status } = req.query

  const condition = []
  const values = []

  if (name) {
    condition.push('name like ?')
    values.push(`%${name}%`)
  }
  if (status !== null && status !== undefined) {
    condition.push('status =?')
    values.push(status)
  }
  const sqlStr = condition.length ? `where ${condition.join(' and ')}` : ''
  console.log(sqlStr);
  const offset = parseInt((page - 1) * pageSize)

  const [response] = await sql.query(`select * from order_product ${sqlStr} `, [...values, parseInt(pageSize), offset])
  const [totalCount] = await sql.query(`select count(*) as count from order_product ${sqlStr} limit ? offset ?`, [...values, parseInt(pageSize), offset])
  console.log(response);
  const total = totalCount[0].count
  res.send(new Response(200, '查询成功', {
    list: response,
    total,
    page,
    pageSize
  }))

})



module.exports = router;

